<?php

/**
 * Created by PhpStorm.
 * User: allen_ios
 * Date: 17/6/12
 * Time: 下午6:47
 */
class ZduRestaurantApiAction extends BaseAction
{
    public $resId; // 模块id
    public $restaurantId;
    public $iPadId;
    public $sRestaurant;
    public $accountId;

    public function _initialize()
    {
        parent::_initialize();

        import("@.ORG.RedisService");
        if(!in_array(strtolower(ACTION_NAME), array('addorder','num','notify','checkorderstatus','cancelorder','cardnotify'))){
            // 获取模块id
            $this->resId = $this->_request('res_id');
            // 获取餐厅id
            $this->restaurantId = $this->_request('restaurant_id');

            if (in_array(strtolower(ACTION_NAME), array('index'))) {
                if (!$this->resId || !$this->restaurantId) {
                    $this->ajaxReturn(array('code' => 10001, 'message' => '参数错误'));
                }
            }else{
                // 获取iPadId
                $this->iPadId = $this->_request('iPad_id');
                if (!$this->resId || !$this->restaurantId || !$this->iPadId) {
                    $this->ajaxReturn(array('code' => 10002, 'message' => '参数错误'));
                }
            }
        }
        $this->accountId = 59;
    }

    /**
     * 获取菜品分类信息
     */
    public function index()
    {
        //获取菜品分类,调用service
        // 实例化服务类Service();第一个参数是文件路径:'ZdRestaurant/ZdRestaurant'
        $this->sRestaurant = Service('BaseRestaurant','',array($this->resId,$this->restaurantId));
        // 查询改餐厅下所有的分类
        $allCategory = $this->sRestaurant->getCategory();
        //并且返回当前店铺最热门的菜谱
        $sGoods = Service('BaseGoods');
        $list = $sGoods->getHotGoods($this->restaurantId);
        array_unshift($allCategory,$list);
		foreach($allCategory as $k=>$v){
			if(is_array($v['goods'])){
				foreach($v['goods'] as $key=>$value){
					$n = 0;
					for($i = 1;$i <= 3;$i++) {
						$n = strpos($value['goods_logo'], '/', $n);
						$i != 3 && $n++;
					}
					$str = substr($value['goods_logo'],$n);
					$allCategory[$k]['goods'][$key]['goods_logo'] = 'http://192.168.3.6/'.$str;
				}
			}
		}
        $this->ajaxReturn(array('code' => 200,'message' => '请求成功','data'=>$allCategory));
    }


    /**
     * 根据category_id获取分类下的菜品信息
     */
    public function getCategoryGoods(){

        $categoryId = $this->_request("category_id");

        $sGoods = Service('BaseGoods');
        // 获取热门菜品-12份
        if ($categoryId==0){
            $list = $sGoods->getHotGoods($this->restaurantId);
        }else{
            $list = $sGoods->getGoods($categoryId,$this->resId);
        }
        if (!$list){
            $this->ajaxReturn(array('code' => 200,'message' => '没有菜品'));
        }
		foreach($list as $key=>$value){
			$n = 0;
			for($i = 1;$i <= 3;$i++) {
				$n = strpos($value['goods_logo'], '/', $n);
				$i != 3 && $n++;
			}
			$str = substr($value['goods_logo'],$n);
			$list[$key]['goods_logo'] = 'http://192.168.31.102'.$str;
		}
        $this->ajaxReturn(array('code' => 200,'message' => '请求成功','data'=>$list));

    }

    /**
     * 订单提交，生成支付宝二维码
     */
    public function AddOrder()
    {
        $post = json_decode($GLOBALS['HTTP_RAW_POST_DATA'],true);
        //检测商品的库存量
        $resId = $post['res_id'];
        $restaurantId = $post['restaurant_id'];
        $iPadId = $post['restaurant_id'];
        if(!$resId||!$restaurantId||!$iPadId){
            $this->ajaxReturn(array('code'=>10003,'message'=>'参数错误'));
        }
        $goodsList = json_decode($post['goods'],true);
        //判断购物车是否为空
        if(count($goodsList)<1){
            $this->ajaxReturn(array('code'=>10004,'message'=>'购物车为空,请选择菜品'));
        }
        $sGoods = Service('BaseGoods');

        //判断库存
        $checkRes = $sGoods->checkOrderStorage($goodsList);
        if(is_array($checkRes)){
            $this->ajaxReturn(array('code'=>10005,'message'=>'库存不足','data'=>$checkRes));
        }

        //生成订单号
        $orderSn = $this->getOrderSn('zduRestaurantApi');
        //生成订单
        $data = array();
        $data['order_sn'] = 'X'.$orderSn['data'];
        $data['order_num'] = 0;
        $data['status'] = 0;
        $data['user_id'] = 0;
        $data['res_id'] = $resId;
        $data['restaurant_id'] = $restaurantId;
        $data['create_time'] = time();
        $data['is_pay_notify'] = 0;
        $data['pay_type'] = 2;//支付宝支付

        //往订单表插入数据
        $sOrder = Service('BaseOrder');
        $ret = $sOrder->addOrder($data);

        if (!$ret){
            $this->ajaxReturn(array('code' => '10006','message' => '生成订单失败'));
        }

        $sum = 0;
        foreach ($goodsList as $key=>$value){
            $goodsInfo = $sGoods->getGoodsInfo($this->resId,$this->restaurantId,$value['goods_id']);
            $sum+= $value['goods_num'] * $goodsInfo['price'];
            $orderGoodsInfo[] = array(
                'order_id' => $ret,
                'goods_id' => $value['goods_id'],
                'restaurant_id' => $restaurantId,
				'order_sn' => $data['order_sn'],
                'goods_num' => $value['goods_num'],
                'create_time' => time(),
                'user_id' => 0,
                'goods_name' => $goodsInfo['goods_name'],
				'print_type'=>$goodsInfo['print_type'],
                'goods_price' => $goodsInfo['price'],
                'goods_logo' => $goodsInfo['goods_logo'],
                'category_id' => $goodsInfo['category_id'],
                'window_id' => M('RestaurantGoodsCategory')->where(array('category_id'=>$goodsInfo['category_id']))->getField('window_id'),
                'order_num' =>0
            );
        }
        $res = $sOrder->addGoodsAll($orderGoodsInfo);
        if (!$res){
            $this->ajaxReturn(array('code' => 10007,'message' => '插入订单物品失败'));
        }
        // 更新订单 order_amount
        $data = array(
            'order_amount'=>$sum
        );
        $updateOrder = $sOrder->updateOrder($ret,$data);
        if (!$updateOrder){
            $this->ajaxReturn(array('code' => 10008,'message' => '出错了'));
        }
        $array =array(
            'order_id'=>$ret,
            'order_sn'=>'X'.$orderSn['data'],
            'order_num'=>0,
            'order_amount'=> sprintf ("%01.2f",$sum)
        );
        return $this->ajaxReturn(array('code' => 200,'message' => '生成订单成功','data'=>$array));

    }

    /*
     * 生成支付二维码
     * $type string  alipay:支付宝  onecard:一卡通
     * $orderSn string  订单号
     */
    public function getPayCode(){
        $post = $this->_post();
        if(!$post['order_sn']||!$post['type']){
            $this->ajaxReturn(array('code' => 10016,'message' => '请选择支付类型'));
        }
        $sOrder = Service('BaseOrder');
        // 获取订单信息
        $orderInfo = $sOrder->getOrderInfo($post['order_id'],'order_sn,restaurant_id,order_num');
        if (!$orderInfo){
            $this->ajaxReturn(array('code' => 10011,'message' => '获取订单失败'));
        }
        if($post['type'] == 'alipay'){
            //生成支付宝二维码
            $sAlipay = Service("Pay/PayFactory");
            $resPay = $sAlipay->createObj('alipay',$this->accountId,$post['order_sn'],'浙大小乐惠点餐'.$orderInfo['order_num'].'号',$notifyUrl='',$returnUrl='',$ledger = array());
            $codePay = $resPay->codePay();
            $array =array(
                'order_sn'=>$post['order_sn'],
                'out_trade_no'=>$codePay['out_trade_no'],
                'pay_code'=>$codePay['qr_code']
            );
            $this->ajaxReturn(array('code' => 200,'message' => '生成支付宝订单成功','data'=>$array));
        }
        if($post['type'] =='oneCard'){
            //生成一个连接给Android端让其生成一个二维码
            $url = "http://wap.xt.beescrm.com/Restaurant/ZduRestaurantApi/oneCardPayByAccount/order_id/".$post['order_id']."/res_id/".$this->resId."/restaurant_id/".$this->restaurantId."/iPad_id/".$this->iPadId;
            $array = array(
                'order_sn'=>$post['order_sn'],
                'out_trade_no'=>$post['order_sn'],
                'pay_code'=>$url
            );
            $this->ajaxReturn(array('code' => 200,'message' => '生成一卡通订单成功','data'=>$array));
        }
    }

    /*
     * 一卡通密码支付跳转页面
     */
    public function oneCardPayByAccount(){
        if($this->isGet()){
            $orderId = $this->_get('order_id');
            if(!$orderId){
                $this->error('系统繁忙，稍后重试！');
            }
            $this->assign('orderId',$orderId);
            $this->assign('resId',$this->resId);
            $this->assign('restaurantId',$this->restaurantId);
            $this->assign('iPadId',$this->iPadId);
            $this->display('onecardpay');
        }
        if($this->isAjax()){
            $resData = $this->_post();
            $orderId = $this->_post('order_id');
            //实例化模型
            $mOrderGoods= D('Base/RestaurantOrderGoods');
            $mOrder = D('Base/RestaurantOrder');

            //查询订单信息
            $info = $mOrder->relation(true)->getByPk($orderId);
            $orderGoodsArray = $mOrderGoods->field('goods_id,goods_num,goods_price,goods_name')->where(array('order_id'=>$orderId))->select();

            //模仿wika的代码
            $goodsNameCampusCard =array();
            foreach ($orderGoodsArray as $k=>$v){
                $goodsNameCampusCard[] = $v['goods_name'];
            }
            $resInfo = array('order_sn'=>$info['order_sn'],'order_num'=>$info['order_num'],'order_amount'=>$info['order_amount'],'pay_type'=>$info['pay_type'],'restaurant'=>'浙大小乐惠点餐','goods_list'=>$orderGoodsArray);
            //跳转地址
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
            $redirectUrl = $protocol . $_SERVER['HTTP_HOST'];
            $thirdUrl = $redirectUrl . '/restaurant/ZduRestaurantApi/cardNotify/res_id/' . $this->resId."/restaurant_id/".$this->restaurantId;
            $errorUrl = $redirectUrl . '/restaurant/ZduRestaurantApi/cardErrorNotify/res_id/' . $this->resId."/restaurant_id/".$this->restaurantId;
            $goodsNameCampusCard = implode(',', $goodsNameCampusCard);
            $campus = Service('CampusCard/CampusCard');
            $resCampus = $campus->campusCardPay($this->accountId,$this->userId,$info, $thirdUrl, $errorUrl,2,$goodsNameCampusCard,$resData['account']);
            wLog(date('Y-m-d H:i:s') . ' orderPay resCampus xlh oneCardPayByAccount: ' . var_export($resCampus,true), 'ZduRestaurantApi');
            if ($resCampus['status'] == 'S') {
                $this->ajaxReturn(array('status'=>'S','message'=>'连接校园卡成功','data'=>$resCampus['data']));
            } else {
                $this->error('系统繁忙，稍后重试！');
            }
        }
    }

    /*
     * 校园卡刷卡确认支付
     */
    public function confirmPayByCard(){
        $account = $this->_post('account');
        /*$password = $this->_post('password');*/
        $orderId = $this->_post('order_id');
        if(!$account || !$orderId){
            $this->ajaxReturn(array('code' => 10017,'message' => '参数错误'));
        }
        //验证密码
        $verify = M('RestaurantAccount')->where(array('account'=>$account,'cut_off'=>0))->find();
        if(!$verify){
            $this->ajaxReturn(array('code' => 10018,'message' => '口令错误'));
        }
        $this->notify($orderId,$type = 'PayByCard');
        $resInfo = $this->orderInfo($orderId);
        $this->ajaxReturn(array('code' => 200,'message' => '支付成功','data'=>$resInfo));
    }

    /*
     * 校园刷卡机支付确认
     */
    public function confirmPayBySchoolCard(){
        $orderId = $this->_post('order_id');
        if(!$orderId){
            $this->ajaxReturn(array('code' => 10017,'message' => '参数错误'));
        }
        $this->notify($orderId,$type ='PayBySchoolCard');
        $resInfo = $this->orderInfo($orderId);
        $this->ajaxReturn(array('code' => 200,'message' => '支付成功','data'=>$resInfo));
    }
    /*
     * 校园卡支付
     *回调
     */
    public function cardNotify(){
        if ($this->_post('thirdsystem')) { //校园卡支付
            $dataResonse = $_POST;
            if (!$dataResonse['sign']) {
                $this->error("参数错误");
            }
            $campus = Service('CampusCard/CampusCard');
            $resCampus = $campus->checkCampusOrder($dataResonse,2);
            if($resCampus['status'] == 'S'){
                $this->notify($resCampus['order_id'],'oneCard');
            }
        }

    }

    /*
     * 支付失败notify
     */
    public function cardErrorNotify(){
        echo 'GG思密达';
    }

    /**
     * 查询订单状态
     */
    public function checkOrderStatus(){

        $orderId = $this->_request("order_id");
        $outTradeNo = $this->_request("out_trade_no");
        $orderSn = $this->_request("order_sn");

        if (!$orderId||!$outTradeNo||!$orderSn){
            $this->ajaxReturn(array('code' => 10009,'message' => '参数错误'));
        }

        $sOrder = Service('BaseOrder');
        $orderInfo = $sOrder->getOrderInfo($orderId,'order_sn,restaurant_id,order_num,pay_type,status');

        //一卡通支付与校园卡刷卡支付
        if($orderInfo['pay_type'] == 4||$orderInfo['pay_type'] == 5){
            if($orderInfo['status'] == 2){
                //通过订单id获取该订单对应的菜系
                $resInfo = $this->orderInfo($orderId);
                $this->ajaxReturn(array('code' => 200,'message' => '支付成功','data'=>$resInfo));
            }else{
                $this->ajaxReturn(array('code' => 10010,'message' => '订单未支付'));
            }
        }
        // 查询订单状态
        $sAlipay = Service("Pay/PayFactory");
        $resPay = $sAlipay->createObj('alipay',$this->accountId,$orderSn,'浙大小乐惠点餐',$notifyUrl='',$returnUrl='',$ledger = array());
        $codePay = $resPay->orderQuery();
        //如果没有付款。返回的是false
        $tradeStatus = $codePay['data']['trade_status'];
        if($tradeStatus == 'WAIT_BUYER_PAY'){ //未支付
            $this->ajaxReturn(array('code' => 10010,'message' => '订单未支付'));
        }
        if($tradeStatus == 'TRADE_SUCCESS' || $tradeStatus == 'RADE_FINISHED'){ //支付成功
            //通过订单id获取该订单对应的菜系
            $resInfo = $this->orderInfo($orderId);
            $this->ajaxReturn(array('code' => 200,'message' => '支付成功','data'=>$resInfo));
        }
        if($tradeStatus == 'TRADE_CLOSED'){ //已撤销或已退款
            $this->ajaxReturn(array('code' => 10014,'message' => '订单已关闭'));
        }
        //订单不存在
        if($codePay ==='ACQ.TRADE_NOT_EXIST'){
            $this->ajaxReturn(array('code' => 10015,'message' => '订单不存在'));
        }
    }

    /*
     * @param Int $orderId  订单号
     * return array
     */
    private function orderInfo($orderId){
        //通过订单id获取该订单对应的菜系
        $mOrderGoods= D('Base/RestaurantOrderGoods');
        $mOrder = D('Base/RestaurantOrder');
        //查询订单信息
        $info = $mOrder->relation(true)->getByPk($orderId);
        $orderGoodsArray = $mOrderGoods->field('goods_id,goods_num,goods_price,goods_name')->where(array('order_id'=>$orderId))->select();
        $resInfo = array('order_sn'=>$info['order_sn'],'order_num'=>$info['order_num'],'order_amount'=>$info['order_amount'],'pay_type'=>$info['pay_type'],'restaurant'=>'浙大小乐惠点餐','goods_list'=>$orderGoodsArray);
        return $resInfo;
    }

    /**
     * 取消订单
     */
    public function cancelOrder(){

        $orderId = $this->_request("order_id");
        $orderSn = $this->_request("order_sn");

        if (!$orderId||!$orderSn){
            $this->ajaxReturn(array('code' => 10009,'message' => '参数错误'));
        }
        $sOrder = Service('BaseOrder');
        // 获取订单信息
        $orderInfo = $sOrder->getOrderInfo($orderId,'order_sn,restaurant_id,status');

        if (!$orderInfo){
            $this->ajaxReturn(array('code' => 10011,'message' => '获取订单失败'));
        }
        /*if ($orderInfo['status'] != 0 && $orderInfo['status'] != 7){
            $this->ajaxReturn(array('code' => 10012,'message' => '订单已完成或已取消'));
        }*/
        $sAlipay = Service("Pay/PayFactory");
        $resPay = $sAlipay->createObj('alipay',$this->accountId,$orderSn,'浙大小乐惠点餐',$notifyUrl='',$returnUrl='',$ledger = array());
        $codePay = $resPay->orderReverse();
        if($codePay['status'] =='S'){
            //更新数据库
            $data = array('status'=>7);

            $res = $sOrder->updateOrder($orderId,$data);
            $this->ajaxReturn(array('code' => 200,'message' => '订单取消成功'));
        }else{
            $this->ajaxReturn(array('code' => 10013,'message' => '订单取消失败'));
        }
    }

    public function num(){
        $orderNum = RedisService::keyExists('zdOrderNum');
        if($orderNum){
            $orderNum = RedisService::incr('zdOrderNum',1);
        }else{
            RedisService::set('zdOrderNum',1);
            $orderNum = RedisService::get('zdOrderNum');
        }
        var_dump($orderNum);
    }

    /**
     * 支付回调
     */
    public function notify($orderId,$type=''){
        //pay_type:1微信支付，2支付宝，4一卡通扫码，5一卡通口令，6刷卡确认支付
        //生成餐桌号$orderId,$type=''
		//$orderId = 59;
        $orderNum = RedisService::keyExists('zdOrderNum');
        if($orderNum){
            $orderNum = RedisService::incr('zdOrderNum',1);
        }else{
            RedisService::set('zdOrderNum',1);
            $orderNum = RedisService::get('zdOrderNum');
        }
        $orderNum = 9000+$orderNum;
        if (!$orderId){
            exit('fail');
        }

        if($type == 'oneCard'){
            M('RestaurantOrder')->where(array('order_id'=>$orderId))->save(array('status'=>2,'pay_type'=>4,'is_pay_notify'=>1,'pay_time'=>time(),'order_num'=>$orderNum));
        }elseif ($type == 'PayByCard'){
            M('RestaurantOrder')->where(array('order_id'=>$orderId))->save(array('status'=>2,'pay_type'=>5,'is_pay_notify'=>1,'pay_time'=>time(),'order_num'=>$orderNum));
        }elseif ($type == 'PayBySchoolCard'){
            M('RestaurantOrder')->where(array('order_id'=>$orderId))->save(array('status'=>2,'pay_type'=>6,'is_pay_notify'=>1,'pay_time'=>time(),'order_num'=>$orderNum));
        } else {
            M('RestaurantOrder')->where(array('order_id'=>$orderId))->save(array('status'=>2,'order_num'=>$orderNum));
        }

        M('RestaurantOrderGoods')->where(array('order_id'=>$orderId))->save(array('pay_status'=>1,'order_num'=>$orderNum));

        $sGoods = Service('Restaurant/BaseGoods');
        // 减库存,加销量
        $sGoods->changeGoodsNum($orderId);

        //通过订单id获取该订单对应的菜系
        $mOrderGoods= D('Base/RestaurantOrderGoods');
        $mOrder = D('Base/RestaurantOrder');
        //查询订单信息
        $hotGoods = array();
        $coldGoods = array();
        $waterGoods = array();
        $info = $mOrder->relation(true)->getByPk($orderId);
        $orderGoodsArray = $mOrderGoods->field('goods_id,goods_num,goods_price,goods_name,print_type')->where(array('order_id'=>$orderId))->select();
        foreach ($orderGoodsArray as $k=>$v){
            if($v['print_type'] ==1){
                $hotGoods[] = $v;
            }elseif ($v['print_type'] ==2){
                $coldGoods[] = $v;
            }elseif ($v['print_type'] ==3){
                $waterGoods[] = $v;
            }
        }
        $printInfo = array('order_sn'=>$info['order_sn'],'order_num'=>$info['order_num'],'order_amount'=>$info['order_amount'],'pay_type'=>$info['pay_type'],'restaurant'=>'浙大小乐惠点餐',
            'push_time'=>time(),'hot_list'=>$hotGoods,'cold_list'=>$coldGoods,'water_list'=>$waterGoods);
        //每次将订单丢入到队列中，先进先出
        $redis = RedisQueueService::getInstance();
        $redis->push('zdxlh_print',$printInfo);
        //$this->useWifiPrintInfo($orderId);
    }
	public function test(){
		$redis = RedisQueueService::getInstance();
		$data = $redis->pull('zdxlh_print');
		/*RedisService::set('zhuhai',1);
		$data = RedisService::get('zhuhai');*/
		print_r($data);
	}


    /**
     * 生成二维码
     */
    public function qrcode()
    {
        $qr_code_message = $this->_get('qr_code');

        if (!$qr_code_message) {
            exit;
        }
        vendor('phpqrcode.phpqrcode');
        $errorCorrectionLevel = 'L';//容错级别
        $matrixPointSize = 12;//生成图片大小
        //生成二维码图片
        QRcode::png(base64_decode($qr_code_message), false, $errorCorrectionLevel, $matrixPointSize, 2, true);
    }

    //检测某商品库存接口
    public function checkStorage(){
        $goodsId = $this->_request('goods_id');
        if(!$goodsId){
            $this->ajaxReturn(array('code'=>10001,'message'=>'参数错误'));
        }
        $mGoods = D('Base/RestaurantGoods');
        $res = $mGoods->field('goods_id,goods_name,goods_sum')->where(array('goods_id' => $goodsId))->find();
        $this->ajaxReturn(array('code'=>200,'message'=>'获取商品库存成功','data'=>$res));
    }
	
	

    /**
     *打印信息
     * @param $orderId
     */
    public function useWifiPrintInfo($orderId)
    {
        //$orderId=8;
        $mOrder = D('Base/RestaurantOrder');
        $mGoods = D('Base/RestaurantGoods');
        $mWindow = D('Base/RestaurantWindow');
        //$orderId = $this->_get('order_id');
        //查询订单信息
        $info = $mOrder->relation(true)->getByPk($orderId);
        //$info = $this->mOrder->relation(true)->getByPk($orderId);
        if ($info) {
            $goodsCold = array();
            $windowInfo = array();

            foreach ($info['RestaurantOrderGoods'] as $key => $v) {
                //查询菜品对应的种类对应档口及打印机信息
                $list = $mGoods->relation('RestaurantGoodsCategory')->getByPk($v['goods_id']);
                //$list = $this->mGoods->relation('RestaurantGoodsCategory')->getByPk($v['goods_id']);
                $wInfo = $mWindow->getByPk($list['window_id']);
                //$wInfo = $this->mWindow->getInfo($list['window_id']);
                $windowInfo[$wInfo['window_id']]['window_id'] = $wInfo['window_id'];
                $windowInfo[$wInfo['window_id']]['print_key'] = $wInfo['print_key'];
                $windowInfo[$wInfo['window_id']]['print_dno'] = $wInfo['print_dno'];
                $windowInfo[$wInfo['window_id']]['print_username'] = $wInfo['print_username'];
                $windowInfo[$wInfo['window_id']]['print_count'] = $wInfo['print_count'];
                $goodsCold[$v['window_id']][] = str_pad($v['goods_name'],18,'　'). str_pad($v['goods_num'],4).'￥'.number_format($v['goods_num']*$v['goods_price'],2)  . '\n';
                $windowInfo[$wInfo['window_id']]['order_amount'] += $v['goods_num']*$v['goods_price'];
                //$goodsHot = $goodsHot . $v['goods_name'] . '    ' . $v['goods_num'] . '     ' . $v['goods_num']*$v['goods_price'] . '\n';
            }
            foreach ($goodsCold as $one=>$on){
                $windowInfo[$one]['goods'] = implode('',$on);
            }
            $headerStr = '';
            if ($this->accountId == 2) {
                $headerStr = '|2http://weixin.qq.com/r/7UzVzQPEGF5nrUeu9xn-' . '\r\n';
            }
            if ($windowInfo) {
                if($info['pay_type'] == 1){
                    $payType = '微信';
                }
                if($info['pay_type'] == 2){
                    $payType = '支付宝';
                }
                if($info['pay_type'] == 4){
                    $payType = '一卡通';
                }
                if($info['pay_type'] == 5){
                    $payType = '校园卡';
                }
                foreach ($windowInfo as $val) {
                    $content = $headerStr .
                        '|5================================' . '\r\n' .
                        '|4餐厅名：' . $info['RestaurantInfo']['restaurant_name'] . '\r\n' .
                        '|4餐号：' . $info['order_num'] . '\r\n' .
                        '|5订单编号：' . $info['order_sn'] . '\r\n' .
                        '|5打印时间:'. date('Y-m-d H:i:s') . '\n' .
                        '|5支付方式:'. $payType . '\n' .
                        '|4------------------------' . '\n' .
                        str_pad('商品名称',18,'　').str_pad('数量',8).'小计'.'\n' .$val['goods'] .
                        '------------------------' . '\n' .
                        '总计：' . $val['order_amount'] .'元'. '\n';
                    $str = $val['print_key'] . $val['print_dno'] . 'aykj';
                    $keyInfo = md5($str);
                    $username = $val['print_username'];
                    $dno = $val['print_dno'];
                    $times = $val['print_count'];
                    $this->useWifiPrint($times, $keyInfo, $content, $username, $dno);
                }
            }
        }
    }

    /**
     *使用wifi打印机打印
     * @param int $times 打印次数
     * @param string $key 加密字符串
     * @param string $content 打印内容
     * @param string $username 官网用户名
     * @param string $dno 设备编号
     * @param int $mode 打印模式（0 混合打印;1文本打印; 2二维码打印;3条码打印）
     * @param string $msgno 订单编号（不传则自动生成）
     * @param string $op 操作类型（pf:打印操作  cx：查询打印机状态 cxdd：查询订单状态）
     * @param string $qr 支付宝二维码图片链接地址（可选）
     * @return array
     */
    function useWifiPrint($times = 3, $key, $content, $username, $dno, $mode = 0, $msgno = '', $op = 'pf', $qr = '')
    {
        /**
         * 返回状态码
         * 0 成功
         * 1 订单发送失败';
         * 200 查询失败';
         * 201 不存在当前设备';
         * 300 二维码打印成功';
         * 301 二维码打印失败';
         * 401 查询订单失败';
         * 900 没有相关操作';
         * 901 操作错误';
         * -2 验证错误';
         * -3 绑定设备不属于该用户';
         * -4 打印类型错误';
         * -5 该用户无效';
         * -7 设备号';
         * -8 参数错误';
         * -102 条形码打印存在汉字';
         * -103 组合打印类型不含有前缀';
         * .
        '序号：' . ($i + 1) . '\r\n' */

        $result = array();
        for ($i = 0; $i < $times; $i++) {
            $url = 'http://121.43.235.40/WS/DealData.ashx';
            $fields = array(
                'op' => $op,
                'content' => $content .
                    '|5================================' . '\r\n' .
                    '|4   青橄榄网络技术支持',
                'key' => $key,
                'unm' => $username,
                'dno' => $dno,
                'mode' => '|' . $mode,
                'msgno' => $msgno,
                'qr' => $qr,
            );
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, count($fields)); // 启用时会发送一个常规的POST请求，类型为：application/x-www-form-urlencoded，就像表单提交的一样。
            curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); // 在HTTP中的“POST”操作。如果要传送一个文件，需要一个@开头的文件名

            ob_start();
            curl_exec($ch);

            $result[] = ob_get_contents();
            ob_end_clean();
        }
        return $result;
    }


    /*
     * 打印服务，极光推送
     * @param $appKey String  app的key  android 提供
     * @param $masterSecret String app的密钥 Android 提供
     * @param $data array  需要推送的数据
     */
    public function aurora($appKey,$masterSecret,$data)
    {
        $appKey = '66bb204994df144f5f26a09e';
        $masterSecret = '8fbfd257d00f90c4673469c9';
        $logFile = '/logs';
        $retryTimes = 60;
        vendor('JPush.Client');
        $client = new Client($appKey, $masterSecret, $logFile, $retryTimes);
        try {
            $response = $client->push()
                ->setPlatform(array('ios', 'android'))
                // 一般情况下，关于 audience 的设置只需要调用 addAlias、addTag、addTagAnd  或 addRegistrationId
                // 这四个方法中的某一个即可，这里仅作为示例，当然全部调用也可以，多项 audience 调用表示其结果的交集
                // 即是说一般情况下，下面三个方法和没有列出的 addTagAnd 一共四个，只适用一个便可满足大多数的场景需求

                // ->addAlias('alias')
                ->addAllAudience()
                /*->addTag(array('tag1', 'tag2'))*/
                // ->addRegistrationId($registration_id)

                ->setNotificationAlert('Hi, JPush')
                ->iosNotification('Hello IOS', array(
                    'sound' => 'sound.caf',
                    // 'badge' => '+1',
                    // 'content-available' => true,
                    // 'mutable-content' => true,
                    'category' => 'jiguang',
                    'extras' => array(
                        'key' => 'value',
                        'jiguang'
                    ),
                ))
                ->androidNotification('Hello Android', array(
                    'title' => 'hello jpush',
                    // 'builder_id' => 2,
                    'extras' => array(
                        'key' => 'value',
                        'jiguang'
                    ),
                ))
                ->message('message content', array(
                    'title' => 'hello jpush',
                    // 'content_type' => 'text',
                    'extras' => array(
                        'key' => 'value',
                        'jiguang'
                    ),
                ))
                ->options(array(
                    // sendno: 表示推送序号，纯粹用来作为 API 调用标识，
                    // API 返回时被原样返回，以方便 API 调用方匹配请求与返回
                    // 这里设置为 100 仅作为示例

                    // 'sendno' => 100,

                    // time_to_live: 表示离线消息保留时长(秒)，
                    // 推送当前用户不在线时，为该用户保留多长时间的离线消息，以便其上线时再次推送。
                    // 默认 86400 （1 天），最长 10 天。设置为 0 表示不保留离线消息，只有推送当前在线的用户可以收到
                    // 这里设置为 1 仅作为示例

                    // 'time_to_live' => 1,

                    // apns_production: 表示APNs是否生产环境，
                    // True 表示推送生产环境，False 表示要推送开发环境；如果不指定则默认为推送生产环境

                    'apns_production' => false,

                    // big_push_duration: 表示定速推送时长(分钟)，又名缓慢推送，把原本尽可能快的推送速度，降低下来，
                    // 给定的 n 分钟内，均匀地向这次推送的目标用户推送。最大值为1400.未设置则不是定速推送
                    // 这里设置为 1 仅作为示例

                    // 'big_push_duration' => 1
                ))
                ->send();
            print_r($response);

        } catch (\JPush\Exceptions\APIConnectionException $e) {
            // try something here
            print $e;
        } catch (\JPush\Exceptions\APIRequestException $e) {
            // try something here
            print $e;
        }
    }
}
